package com.bjtu.boatmq.common.protocol;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.io.Output;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;

public class SourceEncoder extends MessageToByteEncoder<PacketSource> {

    public SourceEncoder(){}
    private Kryo kryo = new Kryo();


//    @Override
//    protected void encode(ChannelHandlerContext channelHandlerContext, PacketSource packetSource, ByteBuf byteBuf) throws Exception {
//
//    }

    @Override
    protected void encode(ChannelHandlerContext ctx, PacketSource ps, ByteBuf out) throws Exception {

        byte[] body = convertToBytes(ps);  //将对象转换为byte
        int dataLength = body.length;  //读取消息的长度
        out.writeInt(dataLength);  //先将消息长度写入，也就是消息头
        out.writeBytes(body);  //消息体中包含我们要发送的数据
    }

    /*@Override
    protected void encode(ChannelHandlerContext ctx, PacketSource ps, ByteBuf out) throws Exception {

        byte[] body = convertToBytes(ps);  //将对象转换为byte
        int dataLength = body.length;  //读取消息的长度
        out.writeInt(dataLength);  //先将消息长度写入，也就是消息头
        out.writeBytes(body);  //消息体中包含我们要发送的数据
    }*/

    private byte[] convertToBytes(PacketSource ps) {

        ByteArrayOutputStream bos = null;
        Output output = null;
        try {
            bos = new ByteArrayOutputStream();
            output = new Output(bos);
            kryo.writeObject(output, ps);
            output.flush();

            return bos.toByteArray();
        } catch (KryoException e) {
            e.printStackTrace();
        }finally{
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(bos);
        }
        return null;
    }

    //public static ByteBuffer encode(PacketSource packetSource) throws IOException {
//        byte[] bytes = SourceEncoder.getBytes(packetSource);
//        ByteBuffer buff = ByteBuffer.wrap(bytes);
//        return buff;
//    }
//    public static byte[] getBytes(PacketSource packetSource) throws IOException{
//        ByteArrayOutputStream bout = new ByteArrayOutputStream();
//        ObjectOutputStream out = new ObjectOutputStream(bout);
//        out.writeObject(packetSource);
//        out.flush();
//        byte[] bytes = bout.toByteArray();
//        bout.close();
//        out.close();
//        return bytes;
//    }
}

